package com.honghh.utils;

import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description:Cookie工具类
 *
 * @author: hh
 * @date: 2018/6/19 15:01
 */
public class CookieUtils {

    /**
     * @param httpServletResponse
     * @param name
     * @param value
     * @param secure              指出浏览器使用的安全协议，例如HTTPS或SSL。  secure=true : 只工作于HTTPS
     * @param maxAge              以秒计算，设置Cookie过期时间。maxAge=0：cookie现在过期,maxAge<0：在浏览器退出时过期。
     * @param domain              仅在域可见 该Cookie所属的网站域名。（apache.org）默认值。
     */
    public static void create(HttpServletResponse httpServletResponse,
                              String name,
                              String value,
                              Boolean secure,
                              Integer maxAge,
                              String domain) {

        Cookie cookie = new Cookie(name, value);
        cookie.setSecure(secure);
        cookie.setMaxAge(maxAge);
        cookie.setDomain(domain);

        //所有路径都可见 指定Cookie适用的路径。
        cookie.setPath("/");

        httpServletResponse.addCookie(cookie);
    }

    public static void clear(HttpServletResponse httpServletResponse, String name, String domain) {
        Cookie cookie = new Cookie(name, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        cookie.setDomain(domain);
        httpServletResponse.addCookie(cookie);
    }

    public static String getValue(HttpServletRequest httpServletRequest, String name) {
        Cookie cookie = WebUtils.getCookie(httpServletRequest, name);
        return cookie != null ? cookie.getValue() : null;
    }
}
